package org.yaukie.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;
import org.yaukie.model.Login;
import org.yaukie.model.Message;
import org.yaukie.websocket.handler.WebSocketHander;

import com.google.gson.GsonBuilder;
 
@Controller
public class IndexController {
	private static final Logger log = Logger.getLogger(IndexController.class);

	@Autowired
	private WebSocketHander  webSocketHander ;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	  public String showLogin(HttpServletRequest request, HttpServletResponse response) {
	    return "login";
	  }
	 
	  @RequestMapping(value = "/loginProcess")
	  public String loginProcess(HttpServletRequest request, HttpServletResponse response ) 
			  throws IOException {
		  String username = request.getParameter("username");
		  username = new String(username.getBytes("ISO-8859-1"), "utf-8");
		  log.debug(username + "登录");
	        HttpSession session = request.getSession();
	        session.setAttribute("SESSION_USERNAME", username);
	        return "msg";
	  }

	@RequestMapping("/index")
	public String index(Model model ){
		model.addAttribute("msg", "websocket");
		return "index";
	}
	
	 	@ResponseBody
	    @RequestMapping(value="/sendMsg",method=RequestMethod.POST)
	    public void sendMsg(HttpServletRequest request,String content){
	 		Message msg =new Message();
	 		 msg.setDate(new Date());
	         msg.setFrom(request.getSession().getAttribute("SESSION_USERNAME")+"");
	         msg.setFromName(request.getSession().getAttribute("SESSION_USERNAME")+"");
	         msg.setTo("ALL");
	         msg.setText(content);
	         webSocketHander.sendMsg(new TextMessage(new GsonBuilder()
	        		 .setDateFormat("yyyy-MM-dd HH:mm:ss")
	        		 .create()
	        		 .toJson(msg)));
	    }
	
}
